import { ComponentType } from 'react'
import Taro, { PureComponent, Config, useState } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { observer, inject } from '@tarojs/mobx'
import { AtInput, AtRadio, AtTextarea, AtButton, AtCheckbox, AtImagePicker } from 'taro-ui'
import { CommonEvent } from "@tarojs/components/types/common";
import { ListItem } from "../../store/input";
import { File } from 'src/store/file'

import ImageLoadFail from '../../assets/icons/img-load-fail.svg'

import './index.scss'

type PageStateProps = {
  indexStore: {
    scanUrl: string,
  }
  inputStore: {
    name: string,
    bearing_load: string,
    construction_unit: string,
    use_unit: string,
    construction_time: string,
    dismantle_time: string,
    remark: string,
    lists: ListItem[],
    level: string,
    btnOn: boolean,
    levelMapStr: Object,
    levelMapInt: Object,
    selectList: Array<number[]>,
    getDataToScanUrl: Function,
    saveCheck: Function,
    clear: Function,
  }
  fileStore: {
    files: File[],
    files2: File[],
    uploadImg: Function,
    preview: Function,
    preview2: Function,
    chooseMessageFile: Function,
    clear: Function,
  }
}

interface Index {
  props: PageStateProps;
}

@inject('indexStore', 'inputStore', 'fileStore')
@observer
class Index extends PureComponent {

  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    navigationBarTitleText: '验收'
  }

  componentWillMount(): void {
    const { indexStore, inputStore } = this.props
    inputStore.getDataToScanUrl(indexStore.scanUrl)
  }

  componentWillUnmount() {
    this.props.inputStore.clear()
    this.props.fileStore.clear()
  }

  // 提交函数
  async submit(): Promise<any> {
    const { inputStore, fileStore } = this.props
    const imgs = fileStore.files.map(item => item.originalUrl).join(',')
    const files = fileStore.files2[0].originalUrl
    inputStore.saveCheck({ image: imgs, files })
  }

  /** data
   * bearing_load: "100"
   * check_type: 3
   * construction_time: "2019-09-27 14:32:24"
   * construction_unit: "北京南天工程"
   * create_time: "0000-00-00 00:00:00"
   * dismantle_time: "0000-00-00 00:00:00"
   * id: 1
   * name: "生产楼3号电缆改造"
   * status: 0
   * update_time: "2019-09-27 14:30:24"
   * use_unit: ""
   */

  /** list
   * create_time: "0000-00-00 00:00:00"
   * id: 1
   * image: "12"
   * level: 1
   * project_id: 1
   * remark: ""
   * status: 1
   * user_name: "小明"
   */

  render () {
    const { inputStore, fileStore } = this.props
    const {
      name,
      bearing_load,
      construction_unit,
      use_unit,
      construction_time,
      dismantle_time,
      level,
      remark,
      lists,
      selectList,
      levelMapStr,
      levelMapInt,
      btnOn,
    } = inputStore
    const selectLevel = [level]
    const [errLoad, setErrLoad] = useState('')
    const checkOptions = [{ value: 2, label: '不合格' }, { value: 1, label: '合格' }]
    const { files, files2 } = fileStore
    const btnDisabled = btnOn || files.length === 0 || files2.length === 0
    const fileName = files2.length === 0 ? '未选择' : files2[0].name
    // 组装预览图片列表
    const imgList: File[][] = lists
      .filter(list => list.image)
      .map(list => {
        return list.image
          .split(',')
          .map(img => ({
            url: `https://project.weitip.com${img}`,
            originalUrl: img
          }))
      })
    return (
      <View className='wrapper'>
        <View className='form-wrap'>
          <View className='title'>
            <Text>基础信息</Text>
          </View>
          <View className='over-layer'>
            <AtInput title='工程名称' value={name || '无'} />
          </View>
          <AtInput title='承重载荷' value={bearing_load || '无'} onChange={(value: string) => inputStore.bearing_load = value} />
          <View className='over-layer'>
            <AtInput title='搭设单位' value={construction_unit || '无'} />
            <AtInput title='使用单位' value={use_unit || '无'} />
            <AtInput title='搭设日期' value={construction_time || '无'} />
            <AtInput title='拆除日期' value={dismantle_time || '无'} />
          </View>
        </View>
        {/* <View className='form-wrap'>
          <View className='title'>
            <Text>验收等级选择</Text>
          </View>
          <AtRadio
            options={[
              { label: '一级', value: '1', desc: '需要填写一级别验收信息' },
              { label: '二级', value: '2', desc: '需要填写二级别验收信息' },
              { label: '三级', value: '3', desc: '需要填写三级别验收信息' }
            ]}
            value={level}
            onClick={(val) => inputStore.level = val}
          />
        </View> */}

        <View className='form-wrap'>
          <View className='title'>
            <Text>验收等级选择</Text>
          </View>
          <View className='input-wrap select-level'>
            <AtCheckbox
              options={[
                { label: '一级', value: '1' },
                { label: '二级', value: '2' },
                { label: '三级', value: '3' }
              ]}
              selectedList={selectLevel}
              onChange={(val) => {
                if (val.length > 1) inputStore.level = val.pop()
                else if (val.length === 0) inputStore.level = level
                else inputStore.level = val[0]
              }}
            />
          </View>
        </View>

        <View className='form-wrap'>
          <View className='title'>
            <Text>验收人</Text>
          </View>
          {
            selectList.map((_, index) => {
              let list
              if (index + 1 > lists.length) {
                list = null
              } else {
                list = lists[index]
              }
              return (
                <AtInput
                  key={_.id}
                  title={`${levelMapStr[index + 1]}级`}
                  placeholder={`请输入${levelMapStr[index + 1]}级验收人`}
                  value={list ? list.user_name : ''}
                  disabled={level !== levelMapInt[index + 1]}
                  onChange={(user_name: string) => {
                    if (!list) {
                      inputStore.lists.push({ user_name })
                    } else {
                      list.user_name = user_name
                    }
                  }}
                />
              )
            })
          }
        </View>
        <View className='form-wrap custom-list-wrap'>
          <View className='title'>
            <Text>验收等级</Text>
          </View>
          {
            selectList.map((_, index) => {
              const disabled = level !== levelMapInt[index + 1]
              return (
                <View className='input-wrap' key={index}>
                  <View className='list-item' key={index}>
                    <View className='list-title'>{`${levelMapStr[index + 1]}级`}</View>
                    <View className='list-value'>
                    <AtCheckbox
                      options={checkOptions.map(opt => ({...opt, disabled}))}
                      selectedList={selectList[index]}
                      onChange={(val) => {
                        if (val.length > 1) selectList[index] = [val.pop()]
                        else selectList[index] = val
                      }}
                    />
                    </View>
                  </View>
                </View>
              )
            })
          }
        </View>
        <View className='form-wrap'>
          <View className='title'>
            <Text>备注</Text>
          </View>
          <View className='textarea-wrap'>
            <AtTextarea
              count={false}
              value={remark}
              onChange={(event: CommonEvent) => inputStore.remark = event.detail.value}
              placeholder='请输入备注...'
            />
          </View>
        </View>
        <View className='form-wrap'>
          <View className='title'>
            <Text>现场图</Text>
          </View>
          <View className='textarea-wrap'>
            <AtImagePicker
              count={1}
              files={files}
              onChange={fileStore.uploadImg.bind(fileStore)}
              onImageClick={fileStore.preview.bind(fileStore)}
            />
          </View>
        </View>
        <View className='form-wrap'>
          <View className='title'>
            <Text>附件</Text>
          </View>
          <View className='textarea-wrap'>
            <AtButton
              type='primary'
              size='small'
              full={false}
              onClick={fileStore.chooseMessageFile.bind(fileStore)}
            >选择</AtButton>
            <View>{fileName}</View>
          </View>
        </View>
        <View className='form-wrap custom-list-wrap'>
          <View className='title'>
            <Text>验收文件</Text>
          </View>
          {
            imgList.map((fileList: File[], index: number) => {
              return (
                <View className='list-item' key={index}>
                  <View className='list-title'>{`${levelMapStr[index + 1]}级`}</View>
                  <View className='list-value'>
                    <View className='grid-wrap'>
                      {
                        fileList.map((file: File, index: number) => (
                          <View className='grid-item' key={index}>
                            <View className='inner-wrapp'>
                              <Image
                                className='preview-img'
                                src={errLoad || file.url}
                                onError={() => setErrLoad(ImageLoadFail)}
                                onClick={() => {
                                  if (errLoad) return
                                  fileStore.preview2(file.url, fileList)
                                }}
                              />
                            </View>
                          </View>
                        ))
                      }
                    </View>
                  </View>
                </View>
              )
            })
          }
        </View>
        <View className='sized-box'></View>
        <View className='btn-fixed'>
          <AtButton type='primary' disabled={btnDisabled} onClick={this.submit.bind(this)}>提交</AtButton>
        </View>
      </View>
    )
  }
}

export default Index  as ComponentType
